import random
import time
from datetime import datetime, timezone, timedelta
from django.http import HttpResponse
import requests
import json
from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad
import base64
import concurrent.futures

from HelloWorld.SimpleCache import SimpleCache


def getBusDetail(type, icon, title, stationName, lineId, stationId, targetOrder):
    url = "https://web.chelaile.net.cn/api/bus/line!encryptedLineDetail.action?s=h5&wxs=wx_app&sign=1&h5RealData=1&v=3.10.43&src=weixinapp_cx&ctm_mp=mp_wx&vc=1&cityId=040&favoriteGray=1&userId=okBHq0Gbv0AMMnBFKQ9mXXpASXG0&h5Id=okBHq0Gbv0AMMnBFKQ9mXXpASXG0&unionId=oSpTTjgMNPh3l6Hdtl6fOkChvMG4&accountId=&secret=&lat=23.124629974365234&lng=113.36199188232422&geo_lat=23.124629974365234&geo_lng=113.36199188232422&gpstype=wgs&geo_type=wgs&scene=1089&lineId={}&targetOrder={}&stationId={}&grey_city=0&stats_referer=search_result&stats_act=switch_stn&cshow=busDetail&localCityId=040&permission=0&cryptoSign=ababc1b7f381a5f440f4b2400e6314c0".format(
        lineId, targetOrder, stationId)

    headers = {
        "Referer": "https://servicewechat.com/wx71d589ea01ce3321/717/page-frame.html"
    }
    response = requests.get(url, headers=headers)

    if response.status_code == 200:
        data = response.content
        data = data.strip(b'**YGKJ').strip(b'YGKJ##')
        data_str = data.decode('utf-8')
        json_data = json.loads(data_str)
        encryptResult = json_data['jsonr']['data']['encryptResult']
        key = b"FF32AE65FBFD19414EAAFF6291A54B42"
        assert len(key) in [16, 24, 32], "Invalid key size"
        cipher_text_bytes = base64.b64decode(encryptResult)
        cipher = AES.new(key, AES.MODE_ECB)
        decrypted_bytes = cipher.decrypt(cipher_text_bytes)
        decrypted_text = unpad(decrypted_bytes, AES.block_size)
        decodeResult = json.loads(decrypted_text.decode('utf-8'))
        result = ""
        distanceToWaitStnList = []
        travelTimeList = []
        for bus in reversed(decodeResult['buses']):
            if bus['distanceToWaitStn'] > 0:
                distanceToWaitStnList.append(bus['distanceToWaitStn'])
            if len(bus['travels']) > 0:
                tip = bus['travels'][0]
                if 'recommTip' in tip.keys():
                    result += tip['recommTip'].strip() + " "
                if 'travelTime' in tip.keys():
                    if tip['travelTime'] >= 0:
                        travelTimeList.append(tip['travelTime'])
        distanceToWaitStn = "{:.2f}".format(min(distanceToWaitStnList) * 0.001) if len(
            distanceToWaitStnList) > 0 else "0.00"
        totalSecond = min(travelTimeList) if len(travelTimeList) > 0 else -1
        minutes = totalSecond // 60
        seconds = totalSecond % 60

        # 美化的内容卡片
        content = '''
                <li class="bus-card {busClass}">
                  <div class="icon-wrapper {iconClass}">
                    <span class="emoji">{icon}</span>
                  </div>
                  <div class="content-wrapper">
                    <div class="line-title {titleClass}">{title}</div>
                    <div class="line-details">
                        {result}
                    </div>
                  </div>
                  <div class="status-wrapper">
                    <a class="status-badge {busClass}">{stationName}</a>
                  </div>
                </li>
            '''
        busClass = ""
        iconClass = ""
        titleClass = ""
        if totalSecond == 0:
            stationName = fixedSpace(
                fixedSpace('<span style="color: white; font-weight: bold;"></span></span>') + "<br>" + fixedSpace(str('<span style="color: white; font-weight: bold;">上车车啦</span>')) + "  " + "<br>" + fixedSpace(
                    str('<span style="color: white;"></span>')) + " " + fixedSpace(str("")) + "<br>")
            busClass = "arriving"
            iconClass = "breathing"
            titleClass = "breathing"
        if totalSecond > 0:
            stationName = fixedSpace(
                fixedSpace('<span style="color: #BA55D3; font-weight: 600;">' + stationName + '</span>') + "<br>" + fixedSpace(str(distanceToWaitStn)) + "公里" + "<br>" + fixedSpace(
                    str(minutes)) + "分" + fixedSpace(str(seconds)) + "秒")
            busClass = "waiting"
        if totalSecond < 0:
            stationName = fixedSpace(
                fixedSpace('<span style="color: #DDA0DD; font-weight: bold;">' + '' + '</span>') + "<br>" + fixedSpace(str('<span style="color: #BA55D3; font-weight: bold;">没车车啦</span>')) + "  " + "<br>" + fixedSpace(
                    str('<span style="color: #BA55D3;"></span>')) + "<br>" + fixedSpace(str("")) + " ")
            busClass = "none"
        content = content.replace("{icon}", icon).replace("{title}", title).replace("{result}", fixedSpace(
            result if result != "" else "")).replace("{stationName}", stationName).replace("{busClass}", busClass).replace("{iconClass}", iconClass).replace("{titleClass}", titleClass)
        return type + "|" + content + "|" + str(totalSecond)

    else:
        return "请求失败"


def thread(argsList):
    with concurrent.futures.ThreadPoolExecutor() as executor:
        futures = [executor.submit(getBusDetail, **args) for args in argsList]
        concurrent.futures.wait(futures)
        results = [future.result() for future in futures]
        goList = []
        backList = []
        # 收集数据并按剩余时间排序
        goData = []
        backData = []
        for result in results:
            res = result.split("|")
            type = res[0].strip()
            content = res[1].strip()
            totalSecond = int(res[2].strip()) if res[2].strip() != "-1" else -1

            if type == "go":
                goData.append({"content": content, "time": totalSecond})
            if type == "back":
                backData.append({"content": content, "time": totalSecond})

        # 按剩余时间排序（从小到大）
        goData.sort(key=lambda x: x["time"] if x["time"] >= 0 else 999999)
        backData.sort(key=lambda x: x["time"] if x["time"] >= 0 else 999999)

        # 提取排序后的内容
        goList = [item["content"] for item in goData]
        backList = [item["content"] for item in backData]

        goContent = '''
            <div id="go-content" class="tab-content active">
                <ul class="bus-list">
                    {content}
                </ul>
            </div>
        '''
        backContent = '''
            <div id="back-content" class="tab-content">
                <ul class="bus-list">
                   {content}
                </ul>
            </div>
        '''
        goContent = goContent.replace("{content}", "".join(goList))
        backContent = backContent.replace("{content}", "".join(backList))

        # 手机端优化的标签切换
        updateTime = datetime.now(timezone(timedelta(hours=8))).strftime("%Y-%m-%d %H:%M:%S")
        # 地图内容容器
        mapContent = '''
            <div id="map-content" class="tab-content">
                <div class="map-container">
                    <div id="map-canvas" class="map-canvas"></div>
                    <div id="map-swipe-layer" class="map-swipe-layer"></div>
                </div>
            </div>
        '''
        tabContainer = f'''
            <div class="tab-container">
                <div class="update-time">
                    <span class="time-icon">🕐</span>
                    <span class="time-text">最近更新：{updateTime}</span>
                </div>
                <div class="tab-header three-tabs">
                    <button class="tab-btn active" onclick="changeTab(0, 'right')">
                        <span class="btn-icon">🧱</span>
                        <span class="btn-text">上班搬砖方向</span>
                    </button>
                    <button class="tab-btn" onclick="changeTab(1, 'none')">
                        <span class="btn-icon">🚦</span>
                        <span class="btn-text">实时路况</span>
                    </button>
                    <button class="tab-btn" onclick="changeTab(2, 'left')">
                        <span class="btn-icon">🏡</span>
                        <span class="btn-text">回家躺床方向</span>
                    </button>
                </div>
                <div class="tab-body">
                    {goContent + mapContent + backContent}
                </div>
            </div>
        '''

        # 底部信息
        footer = '''
        '''

        # CSS样式 - 手机端优化 + 放大80% + 防闪烁
        style = '''
            <style>
                /* 防止字体闪烁 */
                @font-face {
                    font-family: 'System Font';
                    src: local('.SFNSText'), local('Segoe UI'), local('Roboto'), local('Helvetica Neue');
                    font-display: swap;
                }

                * {
                    margin: 0;
                    padding: 0;
                    box-sizing: border-box;
                }

                html {
                    /* 防止页面跳动 */
                    -webkit-font-smoothing: antialiased;
                    -moz-osx-font-smoothing: grayscale;
                    text-rendering: optimizeLegibility;
                }

                body {
                    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
                    background: none;
                    min-height: 100vh;
                    padding: 0;
                    margin: 0;
                    overflow-x: hidden;
                    /* 优化渲染 */
                    -webkit-backface-visibility: hidden;
                    backface-visibility: hidden;
                    perspective: 1000;
                }

                .tab-container {
                    background: transparent;
                    border-radius: 0 0 0 0;
                    padding: 24px 32px 68px 32px;
                    min-height: calc(100vh - 216px);
                    box-shadow: none;
                    /* 优化渲染 */
                    -webkit-backface-visibility: hidden;
                    backface-visibility: hidden;
                    will-change: transform;
                }

                .update-time {
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    gap: 8px;
                    margin-bottom: 16px;
                    padding: 8px 16px;
                    border-radius: 16px;
                    background: transparent;
                    color: #BA55D3;
                    font-size: 1.3em;
                    font-weight: 500;
                    text-align: center;
                    border: none;
                    /* 轻微阴影 */
                    box-shadow: 0 2px 8px rgba(186, 85, 211, 0.08);
                    /* 优化渲染 */
                    -webkit-backface-visibility: hidden;
                    backface-visibility: hidden;
                }

                .time-icon {
                    font-size: 1.5em;
                }

                .time-text {
                    font-size: 1em;
                    white-space: nowrap;
                    color: #333;
                }

                .tab-header {
                    display: flex;
                    gap: 16px;
                    margin-bottom: 32px;
                    padding: 10px;
                    border-radius: 32px;
                    position: sticky;
                    top: 0;
                    z-index: 100;
                    /* 轻微阴影 */
                    box-shadow: 0 4px 16px rgba(186, 85, 211, 0.1);
                    /* 优化渲染 */
                    -webkit-backface-visibility: hidden;
                    backface-visibility: hidden;
                    will-change: transform;
                }

                /* 3个tab时的样式 */
                .tab-header.three-tabs {
                    gap: 10px;
                }

                .tab-header.three-tabs .tab-btn {
                    flex: 1;
                    padding: 18px 12px;
                    font-size: 1.5em;
                }

                .tab-header.three-tabs .btn-icon {
                    font-size: 1.8em;
                }

                .tab-header.three-tabs .btn-text {
                    font-size: 0.85em;
                }

                .tab-btn {
                    flex: 1;
                    border: none;
                    padding: 20px 18px;
                    background: rgba(221, 160, 221, 0.1);
                    border-radius: 24px;
                    font-size: 1.8em;
                    font-weight: 600;
                    cursor: pointer;
                    transition: all 0.3s ease;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    gap: 10px;
                    color: #BA55D3;
                    border: 2px solid rgba(186, 85, 211, 0.2);
                    -webkit-tap-highlight-color: transparent;
                    touch-action: manipulation;
                    /* 轻微阴影 */
                    box-shadow: 0 3px 12px rgba(186, 85, 211, 0.12);
                    /* 优化渲染 */
                    -webkit-backface-visibility: hidden;
                    backface-visibility: hidden;
                    will-change: transform;
                    /* 确保按钮不会换行 */
                    white-space: nowrap;
                    text-overflow: ellipsis;
                    overflow: hidden;
                }

                .tab-btn.active {
                    background: linear-gradient(135deg, #DDA0DD 0%, #BA55D3 100%);
                    color: white;
                    box-shadow: 0 8px 32px rgba(186, 85, 211, 0.4);
                    animation: tabBreathing 2s ease-in-out infinite;
                    border: 2px solid rgba(186, 85, 211, 0.5);
                }

                @keyframes tabBreathing {
                    0%, 100% {
                        transform: scale(1.02);
                    }
                    50% {
                        transform: scale(1.05);
                    }
                }

                .tab-btn:active {
                    transform: scale(0.98);
                }

                .btn-icon {
                    font-size: 2.2em;
                    flex-shrink: 0;
                }

                .btn-text {
                    font-size: 1em;
                    flex-shrink: 1;
                    overflow: hidden;
                    text-overflow: ellipsis;
                }

                .tab-content {
                    display: none;
                }

                .tab-content.active {
                    display: block;
                    opacity: 1;
                }

                @keyframes fadeInUp {
                    from {
                        opacity: 0;
                        transform: translateY(27px);
                    }
                    to {
                        opacity: 1;
                        transform: translateY(0);
                    }
                }

                .bus-list {
                    list-style: none;
                    display: flex;
                    flex-direction: column;
                    gap: 32px;
                    padding: 0;
                }

                .bus-card {
                    background: rgba(255, 255, 255, 0.95);
                    border-radius: 49px;
                    padding: 43px 38px;
                    display: flex;
                    align-items: center;
                    gap: 38px;
                    box-shadow: 0 6px 28px rgba(186, 85, 211, 0.12);
                    border: 2px solid rgba(221, 160, 221, 0.3);
                    transition: box-shadow 0.25s ease, background 0.25s ease;
                    position: relative;
                    overflow: hidden;
                    -webkit-tap-highlight-color: transparent;
                    touch-action: manipulation;
                    /* 优化渲染 */
                    -webkit-backface-visibility: hidden;
                    backface-visibility: hidden;
                    will-change: transform;
                    /* 防止动画期间被其他样式打断 */
                    transform: translateZ(0);
                }

                .bus-card.arriving {
                    animation: swing 1.5s ease-in-out infinite !important;
                    transform-origin: center center !important;
                    transition: none !important;
                }

                .bus-card.arriving:active {
                    animation: swing 1.5s ease-in-out infinite !important;
                }

                .bus-card::before {
                    content: '';
                    position: absolute;
                    top: 0;
                    left: 0;
                    right: 0;
                    height: 9px;
                    background: linear-gradient(90deg, #DDA0DD, #BA55D3);
                    transform: scaleX(0);
                    transition: transform 0.3s ease;
                }

                .bus-card:active {
                    box-shadow: 0 5px 27px rgba(0, 0, 0, 0.1);
                }

                .bus-card:hover::before {
                    transform: scaleX(1);
                }

                /* 从左到右滑动动画 */
                .slide-in-left {
                    animation: slideInLeft 0.9s cubic-bezier(0.34, 1.56, 0.64, 1) forwards;
                    /* 强制使用GPU加速，避免渲染问题 */
                    will-change: transform;
                }

                @keyframes slideInLeft {
                    0% {
                        transform: translate3d(-30px, 0, 0);
                        opacity: 0.3;
                    }
                    40% {
                        transform: translate3d(8px, 0, 0);
                        opacity: 0.8;
                    }
                    65% {
                        transform: translate3d(-6px, 0, 0);
                        opacity: 0.95;
                    }
                    82% {
                        transform: translate3d(3px, 0, 0);
                    }
                    92% {
                        transform: translate3d(-1px, 0, 0);
                    }
                    100% {
                        transform: translate3d(0, 0, 0);
                        opacity: 1;
                    }
                }

                /* 从右向左滑动动画 */
                .slide-in-from-right {
                    animation: slideInFromRight 0.9s cubic-bezier(0.34, 1.56, 0.64, 1) forwards;
                    /* 强制使用GPU加速，避免渲染问题 */
                    will-change: transform;
                }

                @keyframes slideInFromRight {
                    0% {
                        transform: translate3d(30px, 0, 0);
                        opacity: 0.3;
                    }
                    40% {
                        transform: translate3d(-8px, 0, 0);
                        opacity: 0.8;
                    }
                    65% {
                        transform: translate3d(6px, 0, 0);
                        opacity: 0.95;
                    }
                    82% {
                        transform: translate3d(-3px, 0, 0);
                    }
                    92% {
                        transform: translate3d(1px, 0, 0);
                    }
                    100% {
                        transform: translate3d(0, 0, 0);
                        opacity: 1;
                    }
                }

                /* 呼吸动画效果 */
                .breathing {
                    animation: breathing 1.5s ease-in-out infinite;
                }

                @keyframes breathing {
                    0%, 100% {
                        transform: scale(1);
                    }
                    50% {
                        transform: scale(1.05);
                    }
                }

                .icon-wrapper {
                    font-size: 5.4em;
                    width: 130px;
                    height: 130px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    background: linear-gradient(135deg, rgba(221, 160, 221, 0.15), rgba(186, 85, 211, 0.15));
                    border-radius: 32px;
                    box-shadow: 0 6px 20px rgba(186, 85, 211, 0.18);
                    flex-shrink: 0;
                    border: 2px solid rgba(221, 160, 221, 0.5);
                    /* 优化渲染 */
                    -webkit-backface-visibility: hidden;
                    backface-visibility: hidden;
                }

                .content-wrapper {
                    flex: 1;
                    min-width: 0;
                }

                .line-title {
                    font-size: 2.97em;
                    font-weight: 700;
                    color: #BA55D3;
                    margin-bottom: 11px;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                }

                .line-details {
                    font-size: 2.3em;
                    color: #8e44ad;
                    line-height: 1.4;
                    display: -webkit-box;
                    -webkit-line-clamp: 2;
                    -webkit-box-orient: vertical;
                    overflow: hidden;
                }

                .status-wrapper {
                    display: flex;
                    flex-direction: column;
                    align-items: flex-end;
                    gap: 16px;
                    flex-shrink: 0;
                }

                .status-badge {
                    padding: 22px 32px;
                    border-radius: 27px;
                    font-weight: 600;
                    font-size: 2.3em;
                    text-decoration: none;
                    display: inline-block;
                    min-width: 257px;
                    text-align: center;
                    transition: all 0.25s ease;
                    box-shadow: 0 3px 16px rgba(186, 85, 211, 0.1);
                    -webkit-tap-highlight-color: transparent;
                    touch-action: manipulation;
                    /* 优化渲染 */
                    -webkit-backface-visibility: hidden;
                    backface-visibility: hidden;
                    will-change: transform;
                }

                .status-badge:active {
                    transform: scale(0.95);
                }

                @keyframes swing {
                    0% {
                        transform: rotate(0deg);
                    }
                    10% {
                        transform: rotate(1.5deg);
                    }
                    30% {
                        transform: rotate(-1.5deg);
                    }
                    50% {
                        transform: rotate(1deg);
                    }
                    70% {
                        transform: rotate(-1deg);
                    }
                    90% {
                        transform: rotate(0.5deg);
                    }
                    100% {
                        transform: rotate(0deg);
                    }
                }

                .status-badge.arriving {
                    background: linear-gradient(135deg, #DDA0DD 0%, #BA55D3 100%);
                    color: white;
                }

                .status-badge.waiting {
                    background: white;
                    color: #BA55D3;
                    border: 2px solid #DDA0DD;
                }

                .status-badge.waiting:active {
                    background: #BA55D3;
                    color: white;
                }

                .status-badge.none {
                    background: rgba(221, 160, 221, 0.2);
                    color: #BA55D3;
                }

                .app-footer {
                    text-align: center;
                    padding: 41px;
                    color: rgba(255, 255, 255, 0.8);
                    font-size: 2.3em;
                    background: rgba(0, 0, 0, 0.1);
                }

                /* 数字渐变动画 */
                .fade-out {
                    position: relative;
                    display: inline-block;
                    animation: numberFade 1s ease-in-out forwards;
                }

                @keyframes numberFade {
                    0% {
                        font-size: 0.9em;
                        color: transparent;
                        transform: translateY(-5px);
                    }
                    50% {
                        color: #BA55D3;
                        transform: translateY(-2px);
                    }
                    100% {
                        font-size: 1em;
                        color: inherit;
                        transform: translateY(0);
                    }
                }

                /* 手机端适配 */
                @media (max-width: 480px) {
                    .tab-container {
                        padding: 18px 27px 41px 27px;
                        border-radius: 0 0 0 0;
                    }

                    .update-time {
                        font-size: 1.1em;
                        padding: 6px 12px;
                        gap: 6px;
                        margin-bottom: 12px;
                    }

                    .time-icon {
                        font-size: 1.3em;
                    }

                    .tab-btn {
                        padding: 16px 14px;
                        font-size: 1.5em;
                        gap: 8px;
                    }

                    .btn-icon {
                        font-size: 1.9em;
                    }

                    .btn-text {
                        font-size: 0.95em;
                    }

                    .bus-card {
                        padding: 38px 32px;
                        gap: 32px;
                        border-radius: 43px;
                        box-shadow: 0 5px 24px rgba(186, 85, 211, 0.1);
                    }

                    .icon-wrapper {
                        font-size: 4.86em;
                        width: 119px;
                        height: 119px;
                        border-radius: 27px;
                        box-shadow: 0 4px 16px rgba(186, 85, 211, 0.15);
                    }

                    .line-title {
                        font-size: 2.7em;
                    }

                    .line-details {
                        font-size: 2.16em;
                    }

                    .status-badge {
                        padding: 20px 27px;
                        font-size: 2.16em;
                        min-width: 230px;
                        border-radius: 22px;
                        box-shadow: 0 2px 14px rgba(186, 85, 211, 0.1);
                    }
                }

                /* 超小屏幕优化 */
                @media (max-width: 360px) {
                    .tab-container {
                        padding: 16px 22px 32px;
                        border-radius: 0 0 0 0;
                    }

                    .update-time {
                        font-size: 1em;
                        padding: 5px 10px;
                        gap: 5px;
                        margin-bottom: 10px;
                    }

                    .time-icon {
                        font-size: 1.2em;
                    }

                    .time-text {
                        font-size: 0.95em;
                    }

                    .tab-btn {
                        padding: 14px 12px;
                        font-size: 1.3em;
                        gap: 6px;
                    }

                    .btn-icon {
                        font-size: 1.7em;
                    }

                    .btn-text {
                        font-size: 0.9em;
                    }

                    .bus-card {
                        padding: 32px 27px;
                        gap: 27px;
                    }

                    .icon-wrapper {
                        font-size: 4.32em;
                        width: 108px;
                        height: 108px;
                    }
                }

                /* 地图相关样式 */
                .map-container {
                    padding: 24px;
                    background: rgba(255, 255, 255, 0.95);
                    border-radius: 49px;
                    box-shadow: 0 6px 28px rgba(186, 85, 211, 0.12);
                    margin-bottom: 32px;
                    height: calc(100vh - 300px);
                    min-height: 400px;
                }

                .map-canvas {
                    width: 100%;
                    height: 100%;
                    border-radius: 32px;
                    overflow: hidden;
                    box-shadow: 0 4px 20px rgba(186, 85, 211, 0.15);
                    /* 禁用地图触摸交互 */
                    touch-action: none;
                    pointer-events: none;
                }

                /* 地图滑动蒙层 */
                .map-swipe-layer {
                    position: absolute;
                    top: 0;
                    left: 0;
                    width: 100%;
                    height: 100%;
                    pointer-events: auto;
                    z-index: 10;
                    /* 透明但可点击 */
                    background: transparent;
                    /* 优化触摸响应 */
                    -webkit-touch-callout: none;
                    -webkit-user-select: none;
                    user-select: none;
                    /* 允许水平滑动检测 */
                    touch-action: pan-x;
                }

                /* 地图加载动画 */
                .map-loading {
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    height: 500px;
                    background: rgba(221, 160, 221, 0.1);
                    border-radius: 32px;
                    font-size: 2em;
                    color: #BA55D3;
                }

                /* 手机端适配 */
                @media (max-width: 480px) {
                    .map-container {
                        padding: 16px;
                        border-radius: 32px;
                        height: calc(100vh - 250px);
                        min-height: 350px;
                    }

                    .map-canvas {
                        height: 100%;
                        border-radius: 24px;
                    }

                    .map-loading {
                        height: 100%;
                        font-size: 1.5em;
                    }
                }

                @media (max-width: 360px) {
                    .map-container {
                        padding: 12px;
                        height: calc(100vh - 220px);
                        min-height: 300px;
                    }

                    .map-canvas {
                        height: 100%;
                        border-radius: 20px;
                    }

                    .map-loading {
                        height: 100%;
                    }
                }
            </style>
        '''

        # JavaScript - 修复点击 + 流畅交互
        script = '''
            <script src="https://map.qq.com/api/gljs?v=1.exp&key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77"></script>
            <script>
                // 全局函数，确保在页面加载前就可用
                window.changeTab = function(tabIndex, swipeDirection) {
                    const tabBtns = document.querySelectorAll('.tab-btn');
                    const tabContents = document.querySelectorAll('.tab-content');

                    // 切换按钮状态
                    tabBtns.forEach((btn, index) => {
                        if (index === tabIndex) {
                            btn.classList.add('active');
                        } else {
                            btn.classList.remove('active');
                        }
                    });

                    // 切换内容显示
                    tabContents.forEach((content, index) => {
                        if (index === tabIndex) {
                            content.classList.add('active');
                            content.style.display = 'block';
                            // 特殊处理：如果是地图tab（页签1），初始化地图
                            if (index === 1 && !window.mapInitialized) {
                                setTimeout(initMap, 100);
                            } else if (index === 0 || index === 2) {
                                // 公交tab触发动画
                                animateBusCards(content, swipeDirection);
                            }
                        } else {
                            content.classList.remove('active');
                            content.style.display = 'none';
                        }
                    });
                };

                // 为bus-card添加滑动动画
                function animateBusCards(container, swipeDirection) {
                    const busCards = container.querySelectorAll('.bus-card');
                    let hasAnimations = false;

                    busCards.forEach((card, index) => {
                        // 跳过 arriving 卡片，避免干扰摆动动画
                        if (card.classList.contains('arriving')) {
                            console.log('跳过 arriving 卡片，保持摆动动画');
                            return;
                        }

                        // 清除之前的滑入动画class，但不干扰其他动画
                        card.classList.remove('slide-in-left', 'slide-in-from-right');

                        // 确保卡片完全可见
                        card.style.opacity = '1';
                        card.style.visibility = 'visible';

                        // 添加延迟，让动画更流畅
                        setTimeout(() => {
                            let animationClass, timeoutDuration;
                            if (swipeDirection === 'left') {
                                // 左滑：从右向左滑入
                                animationClass = 'slide-in-from-right';
                                timeoutDuration = 900;
                            } else if (swipeDirection === 'right') {
                                // 右滑：从左向右滑入
                                animationClass = 'slide-in-left';
                                timeoutDuration = 900;
                            } else {
                                // 默认情况或点击按钮：从左向右滑入
                                animationClass = 'slide-in-left';
                                timeoutDuration = 900;
                            }

                            // 标记有动画
                            hasAnimations = true;
                            animationInProgress = true;

                            // 添加动画class
                            card.classList.add(animationClass);

                            // 动画结束后清除class和状态
                            setTimeout(() => {
                                card.classList.remove(animationClass);

                                // 检查是否还有其他动画在进行
                                const stillAnimating = Array.from(busCards).some(c =>
                                    !c.classList.contains('arriving') &&
                                    (c.classList.contains('slide-in-left') || c.classList.contains('slide-in-from-right'))
                                );

                                if (!stillAnimating) {
                                    animationInProgress = false;
                                    console.log('所有动画完成，解除锁定');
                                }
                            }, timeoutDuration);
                        }, index * 120);
                    });
                }

                // 页面加载完成后初始化
                document.addEventListener('DOMContentLoaded', function() {
                    // 防止初始化闪烁
                    document.body.style.visibility = 'visible';

                    const htmlEntities = {
                        '&lt;': '<',
                        '&gt;': '>',
                        '&amp;': '&',
                        '&quot;': '"',
                        '&apos;': "'",
                        '&nbsp;': ' ',
                    };

                    // 页面加载时检查是否需要刷新（超过30秒）
                    function checkUpdateTimeOnLoad() {
                        const timeTextElement = document.querySelector('.time-text');
                        if (timeTextElement) {
                            const timeText = timeTextElement.textContent;
                            // 提取时间字符串，格式：最近更新：YYYY-MM-DD HH:MM:SS
                            const timeMatch = timeText.match(/(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/);
                            if (timeMatch) {
                                const lastUpdateTime = new Date(
                                    timeMatch[1],
                                    timeMatch[2] - 1,
                                    timeMatch[3],
                                    timeMatch[4],
                                    timeMatch[5],
                                    timeMatch[6]
                                );
                                const currentTime = new Date();
                                const diffSeconds = Math.floor((currentTime - lastUpdateTime) / 1000);

                                // 如果差距超过30秒，刷新整个页面
                                if (diffSeconds >= 30) {
                                    console.log('页面加载时检测到更新时间超过30秒，执行整页刷新');
                                    window.location.reload();
                                    return;
                                }
                                console.log('页面加载时检查：更新时间差为 ' + diffSeconds + ' 秒，无需刷新');
                            }
                        }
                    }

                    // 立即执行检查
                    checkUpdateTimeOnLoad();

                    // 根据时间自动选择方向
                    const now = new Date();
                    const currentHour = now.getHours();
                    if (currentHour <= 12) {
                        changeTab(0, 'none');
                    } else {
                        changeTab(2, 'none');
                    }

                    // 为当前显示的标签页添加动画
                    const activeContent = document.querySelector('.tab-content.active');
                    if (activeContent) {
                        setTimeout(() => {
                            animateBusCards(activeContent);
                            // 页面加载时触发arriving动画
                            restartSwingAnimation(activeContent);
                        }, 100);
                    }

                    // 数字变化动画
                    function animateNumberChange(element) {
                        element.classList.add('fade-out');
                        setTimeout(() => {
                            element.classList.remove('fade-out');
                        }, 1000);
                    }

                    // 重新触发摆动动画（定义为全局函数）
                    window.restartSwingAnimation = function(container) {
                        if (!container) return;

                        // 使用 requestAnimationFrame 确保在下一帧检查
                        requestAnimationFrame(() => {
                            const arrivingCards = container.querySelectorAll('.bus-card.arriving');
                            console.log('摆动动画检查 - arriving卡片:', arrivingCards.length);

                            // 确保动画正在播放
                            arrivingCards.forEach((card, index) => {
                                // 检查计算后的样式
                                const computedStyle = window.getComputedStyle(card);
                                console.log('卡片 #' + index + ' 动画状态:', computedStyle.animation);
                            });
                        });
                    };

                    // 别名，方便内部调用
                    const restartSwingAnimation = window.restartSwingAnimation;

                    // 局部刷新 - 防闪烁版本 + 防动画打断
                    let isRefreshing = false;
                    let animationInProgress = false;

                    // 初始化地图
                    window.initMap = function() {
                        console.log('初始化地图...');
                        // 南沙地区坐标
                        var center = new TMap.LatLng(22.905022, 113.395082);
                        var mapContainer = document.getElementById('map-canvas');

                        if (!mapContainer) {
                            console.error('地图容器未找到');
                            return;
                        }

                        if (typeof TMap === 'undefined') {
                            console.error('腾讯地图 API 未加载');
                            return;
                        }

                        // 初始化地图
                        var map = new TMap.Map('map-canvas', {
                            zoom: 14.6, // 设置地图缩放级别
                            center: center, // 设置地图中心点坐标
                            baseMap: [
                                { type: 'vector' }, // 设置矢量底图
                                {
                                    type: 'traffic',
                                    opacity: 1,
                                }, // 设置路况底图
                            ],
                        });

                        console.log('地图初始化成功');
                        window.mapInitialized = true;
                    };

                    // 检测是否有动画正在进行
                    function hasAnimationsInProgress() {
                        const animatedElements = document.querySelectorAll('.slide-in-left, .slide-in-from-right');
                        for (let el of animatedElements) {
                            const computedStyle = window.getComputedStyle(el);
                            if (computedStyle.animationName !== 'none') {
                                return true;
                            }
                        }
                        return false;
                    }

                    function refreshContent() {
                        // 如果正在刷新或动画进行中，则延迟刷新
                        if (isRefreshing || animationInProgress) {
                            console.log('刷新延迟，等待动画完成');
                            setTimeout(refreshContent, 500); // 延迟500ms后重试
                            return;
                        }

                        // 检查页面更新时间，如果超过30秒则直接刷新整个页面
                        const timeTextElement = document.querySelector('.time-text');
                        if (timeTextElement) {
                            const timeText = timeTextElement.textContent;
                            // 提取时间字符串，格式：最近更新：YYYY-MM-DD HH:MM:SS
                            const timeMatch = timeText.match(/(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/);
                            if (timeMatch) {
                                const lastUpdateTime = new Date(
                                    timeMatch[1],
                                    timeMatch[2] - 1,
                                    timeMatch[3],
                                    timeMatch[4],
                                    timeMatch[5],
                                    timeMatch[6]
                                );
                                const currentTime = new Date();
                                const diffSeconds = Math.floor((currentTime - lastUpdateTime) / 1000);

                                // 如果差距超过30秒，刷新整个页面
                                if (diffSeconds >= 30) {
                                    console.log('检测到更新时间超过30秒，执行整页刷新');
                                    window.location.reload();
                                    return;
                                }
                            }
                        }

                        isRefreshing = true;

                        fetch(window.location.href)
                            .then(response => response.text())
                            .then(data => {
                                const parser = new DOMParser();
                                const doc = parser.parseFromString(data, "text/html");

                                // 更新时间显示
                                const timeText = doc.querySelector('.time-text');
                                if (timeText) {
                                    const currentTime = new Date();
                                    const timeStr = currentTime.toLocaleString('zh-CN', {
                                        year: 'numeric',
                                        month: '2-digit',
                                        day: '2-digit',
                                        hour: '2-digit',
                                        minute: '2-digit',
                                        second: '2-digit'
                                    }).replace(/\//g, '-');
                                    document.querySelector('.time-text').textContent = '最近更新：' + timeStr;
                                }

                                // 更新上班方向
                                const goNewContent = doc.getElementById("go-content");  // 从新HTML获取
                                const goCurrentElement = document.getElementById("go-content");  // 从当前页面获取

                                if (goNewContent && goCurrentElement) {
                                    // 保存当前的 arriving 动画状态
                                    const arrivingCards = goCurrentElement.querySelectorAll('.bus-card.arriving');
                                    requestAnimationFrame(() => {
                                        goCurrentElement.innerHTML = goNewContent.innerHTML;
                                        console.log('已更新上班方向内容');
                                        // 恢复 arriving 卡片的动画
                                        const newGoContent = document.getElementById("go-content");
                                        const newArrivingCards = newGoContent.querySelectorAll('.bus-card.arriving');
                                        newArrivingCards.forEach((card, index) => {
                                            card.style.animation = 'swing 1.5s ease-in-out infinite';
                                        });
                                    });
                                }

                                // 更新下班方向
                                const backNewContent = doc.getElementById("back-content");  // 从新HTML获取
                                const backCurrentElement = document.getElementById("back-content");  // 从当前页面获取

                                if (backNewContent && backCurrentElement) {
                                    requestAnimationFrame(() => {
                                        backCurrentElement.innerHTML = backNewContent.innerHTML;
                                        console.log('已更新下班方向内容');
                                        // 恢复 arriving 卡片的动画
                                        const newBackContent = document.getElementById("back-content");
                                        const newArrivingCards = newBackContent.querySelectorAll('.bus-card.arriving');
                                        newArrivingCards.forEach((card, index) => {
                                            card.style.animation = 'swing 1.5s ease-in-out infinite';
                                        });
                                    });
                                }
                            })
                            .catch(error => console.error("刷新失败:", error))
                            .finally(() => {
                                setTimeout(() => {
                                    isRefreshing = false;
                                }, 500);
                            });
                    }

                    // 每6秒自动刷新
                    setInterval(refreshContent, 6000);

                    // 添加手势滑动切换tab功能
                    let touchStartX = 0;
                    let touchEndX = 0;
                    let touchStartY = 0;
                    let touchEndY = 0;
                    let isSwipeLocked = false; // 防止滑动期间重复触发
                    const minSwipeDistance = 30; // 最小滑动距离（减小更容易触发）
                    const maxVerticalDistance = 120; // 最大垂直滑动距离（提高容错）

                    // 获取当前活跃的tab索引
                    function getActiveTabIndex() {
                        const tabBtns = document.querySelectorAll('.tab-btn');
                        for (let i = 0; i < tabBtns.length; i++) {
                            if (tabBtns[i].classList.contains('active')) {
                                return i;
                            }
                        }
                        return 0;
                    }

                    // 触摸开始
                    document.addEventListener('touchstart', function(e) {
                        // 检查触摸目标是否在地图滑动蒙层内
                        if (e.target.closest('#map-swipe-layer')) {
                            // 如果正在动画或刷新，不处理滑动
                            if (animationInProgress || isRefreshing) {
                                return;
                            }
                            touchStartX = e.changedTouches[0].screenX;
                            touchStartY = e.changedTouches[0].screenY;
                        } else if (e.target.closest('#map-canvas')) {
                            // 地图区域不处理页签滑动
                            return;
                        } else {
                            // 其他区域正常处理
                            if (animationInProgress || isRefreshing) {
                                return;
                            }
                            touchStartX = e.changedTouches[0].screenX;
                            touchStartY = e.changedTouches[0].screenY;
                        }
                    }, { passive: true });

                    // 触摸结束
                    document.addEventListener('touchend', function(e) {
                        // 检查触摸目标是否在地图滑动蒙层内
                        if (e.target.closest('#map-swipe-layer')) {
                            // 如果正在动画或刷新，或者滑动被锁定，不处理滑动
                            if (animationInProgress || isRefreshing || isSwipeLocked) {
                                return;
                            }
                            touchEndX = e.changedTouches[0].screenX;
                            touchEndY = e.changedTouches[0].screenY;

                            // 锁定滑动，防止重复触发
                            isSwipeLocked = true;
                            handleSwipe();

                            // 300ms后解锁
                            setTimeout(() => {
                                isSwipeLocked = false;
                            }, 300);
                        } else if (e.target.closest('#map-canvas')) {
                            // 地图区域不处理页签滑动
                            return;
                        } else {
                            // 其他区域正常处理
                            if (animationInProgress || isRefreshing || isSwipeLocked) {
                                return;
                            }
                            touchEndX = e.changedTouches[0].screenX;
                            touchEndY = e.changedTouches[0].screenY;

                            // 锁定滑动，防止重复触发
                            isSwipeLocked = true;
                            handleSwipe();

                            // 300ms后解锁
                            setTimeout(() => {
                                isSwipeLocked = false;
                            }, 300);
                        }
                    }, { passive: true });

                    // 处理滑动手势
                    function handleSwipe() {
                        const deltaX = touchEndX - touchStartX;
                        const deltaY = Math.abs(touchEndY - touchStartY);

                        // 如果正在动画或刷新，直接返回
                        if (animationInProgress || isRefreshing) {
                            console.log('动画或刷新中，跳过滑动');
                            return;
                        }

                        // 如果垂直滑动距离过大，忽略（可能是滚动）
                        if (deltaY > maxVerticalDistance) {
                            return;
                        }

                        // 检查是否达到最小滑动距离
                        if (Math.abs(deltaX) < minSwipeDistance) {
                            return;
                        }

                        const currentTabIndex = getActiveTabIndex();

                        // 左滑：切换到下一个tab
                        if (deltaX < 0) {
                            let nextTabIndex;
                            if (currentTabIndex === 0) {
                                // 页签0左滑 → 页签1（实时路况）
                                nextTabIndex = 1;
                            } else if (currentTabIndex === 1) {
                                // 页签1左滑 → 页签2（回家方向）
                                nextTabIndex = 2;
                            } else if (currentTabIndex === 2) {
                                // 页签2左滑 → 页签0（上班方向）
                                nextTabIndex = 0;
                            }
                            changeTab(nextTabIndex, 'left');
                            console.log('左滑，切换到tab:', nextTabIndex);
                        }
                        // 右滑：切换到上一个tab
                        else if (deltaX > 0) {
                            let prevTabIndex;
                            if (currentTabIndex === 0) {
                                // 页签0右滑 → 页签2（回家方向）
                                prevTabIndex = 2;
                            } else if (currentTabIndex === 1) {
                                // 页签1右滑 → 页签0（上班方向）
                                prevTabIndex = 0;
                            } else if (currentTabIndex === 2) {
                                // 页签2右滑 → 页签1（实时路况）
                                prevTabIndex = 1;
                            }
                            changeTab(prevTabIndex, 'right');
                            console.log('右滑，切换到tab:', prevTabIndex);
                        }
                    }

                    // 添加提示信息（可选）
                    const tabContainer = document.querySelector('.tab-container');
                    if (tabContainer) {
                        const hint = document.createElement('div');
                        hint.style.cssText = `
                            position: fixed;
                            bottom: 20px;
                            left: 50%;
                            transform: translateX(-50%);
                            background: rgba(186, 85, 211, 0.9);
                            color: white;
                            padding: 10px 20px;
                            border-radius: 20px;
                            font-size: 0.9em;
                            z-index: 1000;
                            opacity: 0;
                            transition: opacity 0.3s;
                            pointer-events: none;
                            box-shadow: 0 4px 16px rgba(186, 85, 211, 0.25);
                        `;
                        hint.textContent = '👈 左滑右滑可以切换方向哦';
                        document.body.appendChild(hint);

                        // 3秒后显示提示
                        setTimeout(() => {
                            hint.style.opacity = '1';
                            // 3秒后隐藏提示
                            setTimeout(() => {
                                hint.style.opacity = '0';
                                setTimeout(() => {
                                    hint.remove();
                                }, 300);
                            }, 3000);
                        }, 1000);
                    }
                });
            </script>
        '''

        html = tabContainer + footer + style + script
        executor.shutdown()
        return html


def fixedSpace(string):
    return string.rjust(200)


def new_beautiful_bus(request):
    """全新的美观公交查询页面 - 保留全部11条线路 - 手机端优化版"""
    # 配置11条线路（保留全部）
    argsList = []
    # 上班方向（4条）
    argsList.append({"type": "go", "icon": "🫧", "title": "南沙68", "stationName": "上坭小学", "lineId": "002062006270",
                     "stationId": "020-1191", "targetOrder": "24"})
    argsList.append({"type": "go", "icon": "🐯", "title": "番143", "stationName": "太石村", "lineId": "002078056679",
                     "stationId": "020-17335", "targetOrder": "30"})
    argsList.append({"type": "go", "icon": "🐯", "title": "番150B", "stationName": "太石村", "lineId": "020-71512-1",
                     "stationId": "020-17335", "targetOrder": "12"})
    argsList.append({"type": "go", "icon": "🐯", "title": "南沙54", "stationName": "太石村", "lineId": "020-60540-1",
                     "stationId": "020-17335", "targetOrder": "46"})

    # 回家方向（7条）
    argsList.append({"type": "back", "icon": "🫧", "title": "南沙68", "stationName": "区政府东门", "lineId": "002062007902",
                     "stationId": "020-14787", "targetOrder": "7"})
    argsList.append({"type": "back", "icon": "🫧", "title": "南沙68(快)", "stationName": "区政府东门", "lineId": "0020159850909",
                     "stationId": "020-14787", "targetOrder": "5"})
    argsList.append({"type": "back", "icon": "🫧", "title": "南沙65", "stationName": "区政府东门", "lineId": "002061999282",
                     "stationId": "020-14787", "targetOrder": "7"})
    argsList.append({"type": "back", "icon": "🐯", "title": "番143", "stationName": "区政府东门", "lineId": "002027080767",
                     "stationId": "020-14787", "targetOrder": "20"})
    argsList.append({"type": "back", "icon": "🐯", "title": "番150", "stationName": "区政府东门", "lineId": "020-71500-0",
                     "stationId": "020-14787", "targetOrder": "14"})
    argsList.append({"type": "back", "icon": "🐯", "title": "番150B", "stationName": "区政府东门", "lineId": "020-71512-0",
                     "stationId": "020-14787", "targetOrder": "17"})
    argsList.append({"type": "back", "icon": "🐯", "title": "南沙54", "stationName": "东门分站", "lineId": "020-60540-0",
                     "stationId": "020-23469", "targetOrder": "9"})

    results = thread(argsList)
    response = HttpResponse(results)

    # 记录日志
    user_agent = request.META.get('HTTP_USER_AGENT', '未提供 User-Agent')
    print("【新版-简洁版】来源：" + user_agent + "\n请求时间：" + datetime.now(timezone(timedelta(hours=8))).strftime("%Y-%m-%d %H:%M:%S"))
    print("---------------------------------------------------------------------------------------")

    return response
